package com.dddpeter.app.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dddpeter.app.entity.Article;
import com.dddpeter.app.entity.Article.ArticleStatus;
import com.dddpeter.app.entity.ArticleWithStats;
import com.dddpeter.app.repository.ArticleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class ArticleService {
    
    @Autowired
    private ArticleMapper articleMapper;
    
    public List<Article> getAllArticles() {
        return articleMapper.selectList(null);
    }
    
    public Optional<Article> getArticleById(Long id) {
        return Optional.ofNullable(articleMapper.selectById(id));
    }
    
    public List<Article> getArticlesByAuthor(Long authorId) {
        return articleMapper.findByAuthorId(authorId);
    }
    
    public List<Article> getArticlesByStatus(ArticleStatus status) {
        return articleMapper.findByStatus(status);
    }
    
    public List<Article> getPublishedArticles() {
        return articleMapper.findPublishedArticlesOrderByCreatedAtDesc(ArticleStatus.PUBLISHED);
    }
    
    public Article createArticle(Article article) {
        articleMapper.insert(article);
        return article;
    }
    
    public Article updateArticle(Long id, Article articleDetails) {
        Article article = articleMapper.selectById(id);
        if (article == null) {
            throw new RuntimeException("文章不存在，ID: " + id);
        }
        
        article.setTitle(articleDetails.getTitle());
        article.setContent(articleDetails.getContent());
        article.setStatus(articleDetails.getStatus());
        
        articleMapper.updateById(article);
        return article;
    }
    
    public Article publishArticle(Long id) {
        Article article = articleMapper.selectById(id);
        if (article == null) {
            throw new RuntimeException("文章不存在，ID: " + id);
        }
        
        article.setStatus(ArticleStatus.PUBLISHED);
        articleMapper.updateById(article);
        return article;
    }
    
    public Article archiveArticle(Long id) {
        Article article = articleMapper.selectById(id);
        if (article == null) {
            throw new RuntimeException("文章不存在，ID: " + id);
        }
        
        article.setStatus(ArticleStatus.ARCHIVED);
        articleMapper.updateById(article);
        return article;
    }
    
    public void deleteArticle(Long id) {
        Article article = articleMapper.selectById(id);
        if (article == null) {
            throw new RuntimeException("文章不存在，ID: " + id);
        }
        articleMapper.deleteById(id);
    }
    
    public List<Article> searchArticles(String keyword) {
        return articleMapper.findByTitleOrContentContaining(keyword);
    }
    
    public long getArticleCountByAuthor(Long authorId) {
        return articleMapper.countByAuthorId(authorId);
    }
    
    public long getTotalArticleCount() {
        return articleMapper.selectCount(null);
    }
    
    /**
     * 分页查询所有文章
     */
    public IPage<Article> getArticlesPage(int current, int size) {
        Page<Article> page = new Page<>(current, size);
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("created_at");
        return articleMapper.selectPage(page, queryWrapper);
    }
    
    /**
     * 分页查询已发布文章
     */
    public IPage<Article> getPublishedArticlesPage(int current, int size) {
        Page<Article> page = new Page<>(current, size);
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", ArticleStatus.PUBLISHED)
                   .orderByDesc("created_at");
        return articleMapper.selectPage(page, queryWrapper);
    }
    
    /**
     * 分页搜索文章
     */
    public IPage<Article> searchArticlesPage(String keyword, int current, int size) {
        Page<Article> page = new Page<>(current, size);
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.and(wrapper -> wrapper
            .like("title", keyword)
            .or()
            .like("content", keyword))
            .orderByDesc("created_at");
        return articleMapper.selectPage(page, queryWrapper);
    }
    
    /**
     * 分页查询指定分类的文章
     */
    public IPage<Article> getArticlesByCategoryPage(String category, int current, int size) {
        Page<Article> page = new Page<>(current, size);
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", ArticleStatus.PUBLISHED)
                   .like("categories", category)
                   .orderByDesc("created_at");
        return articleMapper.selectPage(page, queryWrapper);
    }
    
    /**
     * 分页查询指定多个分类的文章
     * @param categories 分类列表
     * @param current 当前页码
     * @param size 每页大小
     * @return 分页结果
     */
    public IPage<Article> getArticlesByCategoriesPage(List<String> categories, int current, int size) {
        Page<Article> page = new Page<>(current, size);
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", ArticleStatus.PUBLISHED);
        
        // 如果有多个分类，使用OR条件查询
        if (categories != null && !categories.isEmpty()) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < categories.size(); i++) {
                    if (i > 0) {
                        wrapper.or();
                    }
                    wrapper.like("categories", categories.get(i));
                }
            });
        }
        
        queryWrapper.orderByDesc("created_at");
        return articleMapper.selectPage(page, queryWrapper);
    }
    
    /**
     * 分页查询已发布文章并包含热度和评论数统计
     */
    public List<ArticleWithStats> getPublishedArticlesWithStats(int current, int size) {
        int offset = (current - 1) * size;
        return articleMapper.findPublishedArticlesWithStats(ArticleStatus.PUBLISHED, offset, size);
    }
    
    /**
     * 分页查询指定分类的文章并包含热度和评论数统计
     */
    public List<ArticleWithStats> getArticlesByCategoryWithStats(String category, int current, int size) {
        int offset = (current - 1) * size;
        return articleMapper.findArticlesByCategoryWithStats(ArticleStatus.PUBLISHED, category, offset, size);
    }
    
    /**
     * 获取已发布文章总数
     */
    public Long getPublishedArticlesCount() {
        return articleMapper.countPublishedArticles(ArticleStatus.PUBLISHED);
    }
    
    /**
     * 获取指定分类的已发布文章总数
     */
    public Long getPublishedArticlesCountByCategory(String category) {
        return articleMapper.countPublishedArticlesByCategory(ArticleStatus.PUBLISHED, category);
    }
}
